package gnt.sd.view;

import gnt.sd.R;
import gnt.sd.model.YoutubeData;
import gnt.sd.util.Util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;

public class SDYoutubeView extends RelativeLayout implements OnClickListener {
	HttpURLConnection _connection;
	boolean _connecting;
	Context _context;
	String _id;
	ImageView _thumbImage;
	YoutubeData _youtubeData;
	private ImageView _playImage;
	SDYoutubeView _self;
	Bitmap _bitmap;
	public SDYoutubeView(Context context) {
		super(context);
		_thumbImage = new ImageView(context);
		setPlayImage(new ImageView(context));
		_thumbImage.setScaleType(ScaleType.FIT_XY);
		_thumbImage.setImageResource(R.drawable.music_play_grid_thumb_size);
		getPlayImage().setImageResource(R.drawable.music_play_control_play);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
		getPlayImage().setLayoutParams(layoutParams);
		this._context = context;
		this.addView(_thumbImage, new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		_self = this;
		_connecting = false;
		this.setClickable(true);
		this.setOnClickListener(this);
	}

	public SDYoutubeView(Context context, AttributeSet attrs) {
		super(context, attrs);
		_thumbImage = new ImageView(context);
		setPlayImage(new ImageView(context));
		_thumbImage.setScaleType(ScaleType.FIT_XY);
		_thumbImage.setImageResource(R.drawable.music_play_grid_thumb_size);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
		getPlayImage().setLayoutParams(layoutParams);
		getPlayImage().setImageResource(R.drawable.music_play_control_play);
		this._context = context;
		this.addView(_thumbImage, new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		_self = this;
		_connecting = false;
		this.setClickable(true);
		this.setOnClickListener(this);
	}

	public boolean isConnecting() {
		return _connecting;
	}

	private void cleanUp() {
		if (_connection != null) {
			try {
				_connection.disconnect();
			} catch (Exception ex) {
			}
			_connection = null;
		}
		_connecting = false;
	}
	
	
	protected void finalize() throws Throwable {
		if (_connecting)
			cleanUp();
		super.finalize();
	}
	public void getImage(YoutubeData youtubeData) {
		this._youtubeData = youtubeData;
		_id = Util.hashString(youtubeData.getMediaId());
		String dir = _context.getCacheDir() + "/" + _id + "_ytb.png";
		File file = new File(dir);
		if (file.exists()) {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inTempStorage = new byte[16 * 1024];
			options.inSampleSize = 4;
			_bitmap = BitmapFactory.decodeFile(dir);
			_thumbImage.setImageBitmap(BitmapFactory.decodeFile(dir,options));
			if(getPlayImage().getParent() == null)
				_self.addView(getPlayImage());
		} else {
			if (_connecting)
				return;
			else {
				_connecting = true;
				new DownloadTask().execute(new String[] {
						youtubeData.getThumbnailLink(), "" });
			}
		}
	}

	public class DownloadTask extends AsyncTask<String, Void, Bitmap> {
		// SEND REQUEST
		@Override
		protected Bitmap doInBackground(String... urls) {
			// TODO Auto-generated method stub
			try {
				URL url = new URL(urls[0]);
				_connection = (HttpURLConnection) url.openConnection();
				_connection.setRequestMethod("GET");
				_connection.setDoInput(true);
				_connection.setDoOutput(true);
				int httpCode = _connection.getResponseCode();
				if (httpCode == HttpURLConnection.HTTP_OK) {
					InputStream in = new BufferedInputStream(
							_connection.getInputStream());
					return BitmapFactory.decodeStream(in);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				cleanUp();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap buff) {
			super.onPostExecute(buff);
			if (buff != null) {
				try {
					String dir = _context.getCacheDir() + "/" + _id + "_ytb.png";
					FileOutputStream out = new FileOutputStream(dir);
					buff.compress(Bitmap.CompressFormat.JPEG, 70, out);
					out.flush();
					out.close();
					_thumbImage.setImageBitmap(buff);
					if(getPlayImage().getParent() == null)
						_self.addView(getPlayImage());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					cleanUp();
				}

			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		_context.startActivity(new Intent(Intent.ACTION_VIEW, Uri
				.parse(_youtubeData.getVideoLink())));
	}

	public void setPlayImage(ImageView playImage) {
		this._playImage = playImage;
	}

	public ImageView getPlayImage() {
		return _playImage;
	}
}
